# =================== 导入模块 ===============
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from jwt import exceptions
import jwt
from django.conf import settings



class MyJwtAuthentication(BaseAuthentication):

    def authenticate(self, request):
        # 获取token
        token = request.META.get('HTTP_TOKEN', None)
        # 获取key, 也是加密
        key = settings.SECRET_KEY
        # 开始验证
        try:
            payload = jwt.decode(token, key, True)
        except exceptions.ExpiredSignatureError:
            raise AuthenticationFailed({'code':0, 'error': "Token已失效！"})
        except jwt.DecodeError:
            raise AuthenticationFailed({'code': 0, 'error': "认证失败！"})
        except jwt.InvalidTokenError:
            raise AuthenticationFailed({'code': 0, 'error': "无效的Token！"})
        except:
            raise AuthenticationFailed({'code': 0, 'error': "未知的错误！"})

        return payload, token

# return(payload, token)
# payload -- request.user.id ---> 当前用户的Id
#            request.user.name ---> 当前用户的姓名

# token ---- 可以访问到jwt key   --- > request.token



